package com.chamberlain.framework.web.service;

import com.chamberlain.common.core.domain.entity.SysUser;
import com.chamberlain.common.core.domain.model.LoginUser;
import com.chamberlain.common.enums.UserStatus;
import com.chamberlain.common.exception.ServiceException;
import com.chamberlain.common.utils.MessageUtils;
import com.chamberlain.common.utils.StringUtils;
import com.chamberlain.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author: CYY
 * @date: 2024/3/28
 */
@Service
public class HarmonyUserDetailsServiceImpl implements UserDetailsService {

    private static final Logger log = LoggerFactory.getLogger(HarmonyUserDetailsServiceImpl.class);
    @Resource
    private ISysUserService sysUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = sysUserService.selectUserByUserName(username);

        if (StringUtils.isNull(sysUser))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        }
        else if (UserStatus.DELETED.getCode().equals(sysUser.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        }
        else if (UserStatus.DISABLE.getCode().equals(sysUser.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

//        passwordService.validate(sysUser);
        return createLoginUser(sysUser);
    }

    public UserDetails createLoginUser(SysUser sysUser) {
        return new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, permissionService.getMenuPermission(sysUser));
    }
}
